$(function(){
    var d = new Date(), _year = d.getFullYear(),
    _month = Array("Janvier","Fevrier","Mars","Avril","Mai","Juin","Juillet","Aout","Septembre","Octobre","Novembre","Decembre"),
    _days = Array("Dimanche","Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi"),
    fecha = _days[d.getDay()] +' '+ d.getDate()+' '+ _month[d.getMonth()]+' '+ d.getFullYear(),
    mes = _month[d.getMonth()]+' '+ d.getFullYear(),
    _form = null,
    _iduser = 0,
    _mode = 'insert',
    _idusers = Array(),
    _idT = "",
    editor,
    order = '',
    addedlist = $('#addedlist');

    editorTXT();

    function editorTXT(){
        new nicEditor({
            buttonList: [
            'bold','italic','underline','strikethrough','left','justify','link','unlink','removeformat'
            ],
            iconsPath: './Resouces/js/wysiwyg/nicEditorIcons.gif',
            maxHeight: 300
        }).panelInstance('txtcontenido',{
            hasPanel : true
        });

        editor = nicEditors.findEditor('txtcontenido');
    }

    if(_intUserT!=1) {
        _idT = '_id='+_intUserI+'&';
    }

    disabledControls(true);
    validateform();

    $("#jqGrid").jqGrid({
        // <MODIFICAR>
        url: './Queries/query-actualites.php?'+_idT+'nd='+new Date().getTime(),
        colNames:['int_actualite', 'Actualit&eacute;', 'Publi&eacute;', 'Titre', 'Sections', 'Vote', 'Etat'],
        colModel:[{
            hidden:true, 
            search:false, 
            name:'int_actualite', 
            index:'int_actualite', 
            align:'left'
        },

        {
            name:'var_monthyear', 
            index:'var_monthyear', 
            align:'left'
        },

        {
            name:'dat_creation_act', 
            index:'dat_creation_act', 
            align:'left'
        },

        {
            name:'var_ac_title', 
            index:'var_ac_title', 
            align:'left'
        },

        {
            name:'var_desc_section', 
            index:'var_desc_section', 
            align:'left'
        }, {
            name:'int_vote', 
            index:'int_vote', 
            align:'center'
        },{
            name:'var_htmldesc', 
            index:'var_htmldesc', 
            align:'left'
        }],
        sortname: 'int_actualite',
        sortorder: "desc",
        width: 938,
        height: 400,
        // </MODIFICAR>
		
        loadtext: 'Chargement...',
        datatype: "json",
        pager: $('#jqpager'),
        rowNum:150,
        rowList:[150,300,500],	
        viewrecords: true,
        multiselect: true
    });
		
    function validateform(){
        _form = $("#frmnuevousuario").validate({
            event: "blur",
            rules:{ 
                'txttitle': {
                    required: true
                },
                'txtcontenido': "required",
                'cboseccion': "required",
                'cboestado': "required"	
            },
            messages: {
                'txttitle': "Entrez le titre de l'actualit&eacute;.",
                'txtcontenido': "Entrez le contenu de l'actualit&eacute;",
                'cboseccion': "S&eacute;lectionnez la section.",
                'cboestado': " S&eacute;lectionnez l'&eacute;tat."
            }
        });	
		
        // SAVE FORM 
        $("#frmnuevousuario").submit(function(){
            if(_form.valid()){
                disabledControls(false);
                save_nuevo();	
                disabledControls(true);
            }
            return false;
        });
    };
    
	
    $("#supdate").click(function(){
        var s = $("#jqGrid").getGridParam('selarrrow');
        switch(s.length) {
            case 0:
                messageBox('Avertissement','S&eacute;lectionnez une actualit&eacute; parmi la liste.',"alert");
                break;
            case 1:
                _mode 	= 'update';
                _iduser = s[0]; 
                disabledControls( false );
                defaultControls();
                getActualite( s );				 
                ShowForm();
                break;
            default:
                messageBox('Avertissement','S&eacute;lectionnez une actualit&eacute; &agrave; la fois.',"alert");
                break;
        }
    });
	
    $("#sdelete").click(function(){
        _mode = 'delete';
        var gr = $("#jqGrid").getGridParam('selrow');
	
        if( gr != null ) {
            var s = $("#jqGrid").getGridParam('selarrrow');
            var f = s.toString();
            var j =  f.split(',');
            _idusers = j;
            messageBoxConfirm("Eliminer l'Actualit&eacute", 'Vous avez selection&eacute; '+j.length+" actualit&eacute;(s).<br/>Voulez vous vraiment l'effacer(s)?", "alert");
        } else{
            messageBox('Avertissement','S&eacute;lectionnez les actualit&eacute;s &agrave; effacer.',"alert");
        }
    });
	
    $("#sinsert").click(function(){
        _mode = 'insert';
        disabledControls(false);
        defaultControls();
        ShowForm();
    });
	
    function defaultControls(){
        $('#txttitle').val('');
        editor.setContent('');
        selectCbo( '#cboseccion', "" );
        selectCbo( '#cboestado', '' );
    }
	
    $('#s-dialog-cancelar4').click(function(){
        deleteUsers();
    });
	
    function deleteUsers(){
        var _newdata = "";
        for(var i = 0; i<_idusers.length; i++){
            _newdata += _idusers[i]+'-';
        }
		
        $.post("./?ws=Actualites&act=DeleteActualite", {
            _ids: _newdata, 
            nocache: Math.random()
        }, function(data){

            if(data!="" || data!=" "){
                $('#jqGrid').trigger('reloadGrid');
                alert( $.trim(data) );
                $.modal.close();
            }
			
            $("#login-msg").ajaxError(function(request, settings){ 
                alert(settings.url );
            });
        });
    }
    
    $("#msg-nuevo").hide();

    function ShowForm(){
        if(_mode=='insert') $('#frm-title').html( "Ajouter une actualit&eacute;" );
        else $('#frm-title').html( "Modifier l'Actualit&eacute;" );

        $('#rightnow a').hide();
        $("#msg-nuevo").show();
        $('#gbox_jqGrid').hide();

        $('#txttitle').select();
    }
	
    function messageBox(_title, _msg, _type){
        var _src = './Resouces/images/alert.png';
        switch(_type){
            case "error":
                _src = './Resouces/images/error.png';
                break;
            case "info":
                _src = './Resouces/images/info.png';
                break;
        }
		
        $('#s-dialog-cancelar4').css( {
            display:'none'
        } );
        $('#s-dialog-cancelar3').val( 'Accepter' );
        $('#msg-title').html( _title );
		
        $('#msg-image').attr( 'src', _src );
        $('#msg-text').html( _msg );
		
        $("#msg-alert").modal({
            position: [0,0],
            opacity: 45,
            autoResize: true,
            onOpen: function (dialog){
                dialog.overlay.fadeIn('fast', function (){
                    dialog.container.fadeIn('fast', function (){
                        dialog.data.show();
                    });
                });
            }			
        });
    }

    function messageBoxConfirm(_title, _msg, _type){
        var _src = './Resouces/images/alert.png';
        switch(_type){
            case "error":
                _src = './Resouces/images/error.png';
                break;
            case "info":
                _src = './Resouces/images/info.png';
                break;
        }
		
        $('#msg-title').html( _title );
        $('#s-dialog-cancelar4').css( {
            display:'inline'
        } );
        $('#s-dialog-cancelar3').val( 'Annuler' );
		
        $('#msg-image').attr( 'src', _src );
        $('#msg-text').html( _msg );
		
        $("#msg-alert").modal({
            position: [0,0],
            opacity: 45,
            autoResize: true,
            onOpen: function (dialog){
                dialog.overlay.fadeIn('fast', function (){
                    dialog.container.fadeIn('fast', function (){
                        dialog.data.show();
                    });
                });
            }			
        });
    }

    $("#s-dialog-cancelar2").click(function(){
        $("#msg-nuevo").hide();
        $('#gbox_jqGrid').show();
        $('#rightnow a').show();
        addedlist.empty();
        list.empty();
        order = '';
    });

    $("#s-dialog-cancelar3").click(function(){
        $.modal.close();
    });

    function disabledControls(val){
        if (val) {
            $('#txttitle').attr('disabled','-1');
            $('#txtcontenido').attr('disabled','-1');
            $('#cboseccion').attr('disabled','-1');			
            $('#cboestado').attr('disabled','-1');
            $('#btnguardar').attr('disabled','-1');
        } else {
            $('#txttitle').removeAttr('disabled');
            $('#txtcontenido').removeAttr('disabled');
            $('#cboseccion').removeAttr('disabled');
            $('#cboestado').removeAttr('disabled');
            $('#btnguardar').removeAttr('disabled');
        }
    }

    function save_nuevo(){       
        var _funct = 'InsertActualite';

        if(_mode == 'update'){
            _funct = 'UpdateActualite';
        }

        $.post("./?ws=Actualites&act="+_funct, {
            _id: _iduser, 
            txttitle: $('#txttitle').val(), 
            txtcontenido: editor.getContent(), 
            cboseccion: $('#cboseccion').val(), 
            cboestado: $('#cboestado').val(),
            order: getOrder(),
            dat_fecha:fecha, 
            dat_mes:mes, 
            nocache: Math.random()
        }, function(data){
            if(data!="" || data!=" "){
                $('#jqGrid').trigger('reloadGrid');
                alert( $.trim(data) );
                $("#msg-nuevo").hide();
                $('#gbox_jqGrid').show();
                $('#rightnow a').show();
                addedlist.empty();
                list.empty();
                order = '';
            }           
            $("#login-msg").ajaxError(function(request, settings){ 
                alert(settings.url );
            });
        });
    }

    function getActualite(_id){
        $("#frmnuevousuario").disabled();
        $.post("./?ws=Actualites&act=getActualite", {
            _id:_id,
            nocache: new Date().getTime()
        }, function(e){
            if(e) {
                setActualiteData(e.response);
            } else {
                alert("Oups ! une erreur s\'est produite.");
            }
        }, 'json');
    }

    function setActualiteData(d) {
        $('#txttitle').val(d.title); 
        editor.setContent(d.content);
        selectCbo('#cboseccion', d.id_section);
        selectCbo('#cboestado', d.state);
        order = d.order;
        $('#txttitle').select();
        sections.trigger('change');
    }

    function selectCbo(_idcbo, _intval){
        $(_idcbo+" option").each(function(){
            if($(this).val() == _intval) $(this).attr('selected','selected'); 
        });
    }

    //    $( "#selectable" ).selectable({
    //        filter: 'li',
    //        stop: function(){
    ////            order = [];
    ////            $(".ui-selected", this).each(function(){
    ////                order.push($("#selectable li").index(this));
    ////            });
    //        }
    //    });

    var list = $('#selectable'), sections = $('#cboseccion'), msg_gal = "Oups, aucun album pour cette section";

    sections.bind('change',function(){
        $("option:selected", this).each(function(){
            addedlist.empty();
            if ($(this).val() != '') {
                $("#frmnuevousuario").disabled();
                if ($(this).val() < 3) {
                    sections.xrequest('start');
                } else {
                    list.xrequest('set',{
                        data: {
                            id: $(this).val()
                        }
                    });
                    list.xrequest('start');
                }
            } else {
                list.empty().text(msg_gal);
            }            
        }); 
    });

    sections.xrequest({
        url: './?ws=Photos&act=getGaleries',
        type: 'GET',
        csrf: false,
        onSuccess: function(e) {
            if (e) {
                $("#frmnuevousuario").enabled();
                if (e.header.code == 4) {
                    if (e.response) {
                        list.empty();
                        addedlist.empty();
                        buildAllGalleries(e.response);
                    } else {
                        list.text(msg_gal);
                    }
                } else {
                    alert("Oups ! une erreur s\'est produite lors de l\'envoi.");
                }
            }
        }
    });
 
    list.xrequest({
        url: './?ws=Photos&act=galleriesBySectionId',
        type: 'GET',
        csrf: false,
        onSuccess: function(e) {
            if (e) {
                $("#frmnuevousuario").enabled();
                if (e.header.code == 4) {
                    list.empty();
                    if (e.response) {
                        addedlist.empty();
                        buildGallerieTitles(e.response);
                    } else {
                        list.text(msg_gal);
                    }
                } else {
                    alert("Oups ! une erreur s\'est produite lors de l\'envoi.");
                }
            }
        }
    });

    function buildGallerieTitles(rows) {
        $('<h3/>').addClass('selectable_title').text($('option:selected',sections).text()).appendTo(
            $('<div>').attr('id','id'+$('option:selected',sections).val()).appendTo(list)
            );
        for (var i in rows) {
            list.append($('<li/>').attr({
                'lang': rows[i].int_id_gallery
            }).text(rows[i].var_title_gallery).addClass('ui-state-default').prepend($('<a>').attr({
                'href': 'javascript:;'
            }).addClass('add_left_icon')));
        }

        if (order) {
            selectGalleriesByOrder(order);
        }
    }

    function buildAllGalleries(rows) {
        $("option", sections).each(function(){
            if ($(this).val() > 1) {
                $('<h3/>').addClass('selectable_title').text($(this).text()).appendTo(
                    $('<div>').attr('id', 'id'+ ($(this).val() == 2 ? 1 : $(this).val())).hide().appendTo(list)
                    );
            }
        });

        for (var i in rows) {
            $('#id'+rows[i].int_id_section).addClass('selectable_group').append(
                $('<li/>').attr({
                    'lang': rows[i].int_id_gallery
                }).text(rows[i].var_title_gallery).addClass('ui-state-default').prepend($('<a>').attr({
                    'href': 'javascript:;'
                }).addClass('add_left_icon'))).show();
        }
        
        if (order) {
            selectGalleriesByOrder(order);
        }
    }
    
    function selectGalleriesByOrder(o) {
        var e;
        for (var i in o) {
            e = $("li[lang="+o[i]+"]", list).hide().clone();
            addedlist.append(e.show());
            $('a',e).removeClass().addClass('close_icon');
        }
        order = '';
    }
    
    function getOrder() {
        var ord = [];
        if ($('li.ui-state-default', addedlist).length > 0) {
            $('li.ui-state-default', addedlist).each(function(){
                ord.push($(this).attr('lang'));
            });
        } else {
            ord = '';
        }
       
        return ord.toString();
    }
    
    //    $('#addtolist').click(function(){
    //        var e;
    //        $('li.ui-selected',list).each(function(){
    //            e = $(this).hide().clone();
    //            addedlist.append(e.show());
    //            $('a',e).removeClass().addClass('close_icon');
    //        });
    //    });

    $('a', list).live('click',function(){
        var e = $(this).parent().hide().clone();
        addedlist.append(e.show());
        $('a',e).removeClass().addClass('close_icon');
    });
    
    $('a', addedlist).live('click',function(){
        $('li[lang='+$(this).parent().attr('lang')+']', list).show();
        $(this).parent().remove();
    });
});